import os
import time
from flask import Flask, render_template_string, request

app = Flask(__name__)

# ----------------------------
# 日志配置
# ----------------------------
LOG_FILE = "/os/server.log"
MAX_LOG_SIZE = 10 * 1024 * 1024  # 10 MB

def write_log(msg):
    if os.path.exists(LOG_FILE) and os.path.getsize(LOG_FILE) > MAX_LOG_SIZE:
        os.remove(LOG_FILE)
    timestamp = time.strftime("%Y-%m-%d %H:%M:%S")
    with open(LOG_FILE, "a", encoding="utf-8") as f:
        f.write(f"[{timestamp}] {msg}\n")

# ----------------------------
# 矿机状态
# 格式: name: (ip, cpu, mem, temp, last_upload_ts)
# ----------------------------
status_data = {}

# ----------------------------
# 接收矿机上传
# ----------------------------
@app.route("/upload", methods=["POST"])
def upload_status():
    name = request.form.get("name")
    cpu = request.form.get("cpu")
    mem = request.form.get("mem")
    temp = request.form.get("temp")
    ip = request.remote_addr
    timestamp = int(time.time())  # 服务器时间为准

    # 更新矿机状态
    status_data[name] = (ip, cpu, mem, temp, timestamp)

    write_log(f"{name} 上传状态: CPU={cpu}%, MEM={mem}%, TEMP={temp}, 服务器响应: OK")
    return "OK"

# ----------------------------
# 辅助函数
# ----------------------------
def now_ts():
    return int(time.time())

def last_time_str(ts):
    return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(ts))

# ----------------------------
# 网页显示
# ----------------------------
@app.route("/")
def index():
    # 删除超过24小时没更新的矿机
    to_delete = []
    now = now_ts()
    for name, (_, _, _, _, last_ts) in status_data.items():
        if now - last_ts > 86400:  # 24小时
            to_delete.append(name)
    for name in to_delete:
        del status_data[name]

    # 记录访问日志
    write_log(f"首页访问: {len(status_data)} 台矿机显示")

    # 读取 HTML 模板
    try:
        with open("/var/www/html/index8080.html", "r", encoding="utf-8") as f:
            html_content = f.read()
    except Exception as e:
        write_log(f"读取 HTML 模板失败: {e}")
        return f"读取 HTML 模板失败: {e}"

    return render_template_string(
        html_content,
        visible_status=status_data,
        total_machines=len(status_data),
        now_ts=now_ts,
        last_time_str=last_time_str
    )

# ----------------------------
# 启动服务
# ----------------------------
if __name__ == "__main__":
    write_log("服务启动，监听 0.0.0.0:8080（无需登录）")
    app.run(host="0.0.0.0", port=8080)
